package main

import (
	"encoding/hex"
	"flag"
	"gitee.com/yangzx6606/core/conn/server"
	"gitee.com/yangzx6606/core/system"
	log "github.com/golang/glog"
)

type EchoServer struct {
	serv server.Server
}

func (s *EchoServer) OnData(packet *server.Packet, args any) {
	if packet.Type == server.PacketTypeConnected {
		log.Info("客户端[", packet.Session.GetAddress(), "]连接成功")
	} else if packet.Type == server.PacketTypeConnectLost {
		log.Info("客户端[", packet.Session.GetAddress(), "]连接断开")
	} else if packet.Type == server.PacketTypeData {
		log.Info("[RX]", hex.EncodeToString(packet.Data))
		err := packet.Session.Write(packet)
		if err != nil {
			log.Error("写入数据失败：", err)
		}
	}
}

func (s *EchoServer) Open() error {
	s.serv.AttachObserver(s, nil)
	return s.serv.Open()
}

func (s *EchoServer) Close() {
	s.serv.Close()
}

func main() {
	var mode = "quic"
	var address = ":8092"
	flag.StringVar(&mode, "mode", mode, "运行模式可选：'tcp'/'quic'")
	flag.StringVar(&address, "address", address, "监听地址，如：:8092")
	flag.Parse()
	var serv *EchoServer
	if mode == "quic" {
		serv = &EchoServer{serv: server.NewQuicServer(address, []string{"media"})}
	}
	if serv != nil {
		err := serv.Open()
		if err != nil {
			log.Error("启动服务失败：", err)
			return
		}
		system.SignalWait()
		serv.Close()
	}

}
